import React from "react";

export function getSlot(slots: SlotsComponent | null | undefined, slot = "default"): React.ReactNode | null {
	if (!slots || !Reflect.has(slots, slot)) return null;
	return slots[slot];
}

/**
 * extends slots
 * @param slots
 * @param excludeKeys
 */
export function extendSlots(slots: SlotsComponent | null, excludeKeys: string[] = []): Recordable<React.ReactNode> | null {
	const slotKeys = Object.keys(slots);
	const ret: any = {};
	slotKeys.map(key => {
		if (excludeKeys.includes(key)) return null;
		ret[key] = () => getSlot(slots, key);
	});
	return ret;
}

export function childrenToMap(children: React.ReactNode | React.ReactNode[]): Recordable<React.ReactNode> {
	const slotArr: React.ReactNode[] = React.Children.toArray(children);
	if (!slotArr || !slotArr.length) return {};
	const slots: SlotsComponent = {};
	slotArr.forEach((ele: React.ReactNode) => {
		slots[(ele?.props?.slot as string) ?? "default"] = ele;
	});
	return slots;
}
